const localData = localStorage.getItem('pz_v3pz')
// 配合插件数据持久化处理
const state = localData ? localData.menu : {
  isCollapse: false,
  selectMenu: [],
  routerList: [],
  menuActive: '1-1'
}

const mutations = {
  collapseMenu(state) {
    state.isCollapse = !state.isCollapse
  },
  addMenu(state, payload) {
    if (state.selectMenu.findIndex(item => item.path === payload.path) === -1) {
      state.selectMenu.push(payload)
    }
  },
  closeMenu(state, payload) {
    const index = state.selectMenu.findIndex(val => val.name === payload.name)
    state.selectMenu.splice(index, 1)
  },
  dnamicMenu(state, { payload, router }) {
    /**
     * 类似
     * const componentsContext = require.context('./components', true, /index.vue$/)
     * 
     * componentsContext.keys().forEach((componentPath) => {}
     *  const componentConfig = componentsContext(componentPath).default
     *  Vue.component(componentConfig.name,componentConfig)
     * })
     */
    // 通过glob导入文件
    const modules = import.meta.glob('../views/**/**/*.vue')
    const routerSet = (source) => {
      source.forEach(item => {
        // 判断没有子菜单，拼接路由数据
        if (!item.children) {
          const url = `../views${item.meta.path}/index.vue`
          // 拿到获取vue组件
          item.component = modules[url]
        } else {
          routerSet(item.children)
        }
      })
    }
    routerSet(payload)
    // 拿到完整的路由数据
    state.routerList = payload

    // 更新动态路由，在登录和刷新后main.js中同时处理
    payload.forEach(item => {
      router.addRoute('main', item)
    })
  },
  // 设置当前激活的路由
  updateMenuActive(state, payload) {
    state.menuActive = payload
  }
}

export default {
  state,
  mutations
}
